<script setup lang="ts">
import { ref, reactive, nextTick, watch, onUnmounted } from "vue";
import {
  Plus,
  Edit,
  Delete,
  Share,
  Star,
  ChatDotRound,
  Menu,
  Grid
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance } from "element-plus";

interface Comment {
  id: number;
  userId: number;
  username: string;
  avatar: string;
  content: string;
  createTime: string;
  replyTo?: number;
}

interface SharingPost {
  id: number;
  userId: number;
  username: string;
  avatar: string;
  title: string;
  content: string;
  images: string[];
  createTime: string;
  updateTime: string;
  likeCount: number;
  commentCount: number;
  isLiked?: boolean;
  comments?: Comment[];
}

// 状态定义
const loading = ref(false);
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const currentPost = ref<SharingPost | null>(null);

// 表单数据
const postForm = reactive({
  title: "",
  content: "",
  images: [] as string[]
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: "请输入标题", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  content: [
    { required: true, message: "请输入内容描述", trigger: "blur" },
    { min: 5, max: 500, message: "长度在 5 到 500 个字符", trigger: "blur" }
  ],
  images: [{ required: true, message: "请上传至少一张图片", trigger: "change" }]
};

// 分享列表数据
const sharingList = ref<SharingPost[]>([
  {
    id: 1,
    userId: 1,
    username: "花想容",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服春游随拍",
    content:
      "今天和闺蜜一起去公园春游，穿着新买的汉服，拍了好多美照，分享给大家~",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-20 14:30:00",
    updateTime: "2024-01-20 14:30:00",
    likeCount: 128,
    isLiked: true
  },
  {
    id: 2,
    userId: 2,
    username: "清辞",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服写真 | 明制袄裙",
    content:
      "分享一组明制袄裙的写真，这套衣服真的很适合拍照，喜欢这种复古典雅的风格。感谢摄影师的用心拍摄！",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-19 10:15:00",
    updateTime: "2024-01-19 10:15:00",
    likeCount: 256,
    isLiked: false
  },
  {
    id: 3,
    userId: 3,
    username: "墨兮",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服日常 | 宋制对襟襦裙",
    content:
      "今天穿了宋制对襟襦裙去逛街，这套衣服真的很适合日常穿搭，舒适又好看。路人都说很好看呢！",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-18 16:45:00",
    updateTime: "2024-01-18 16:45:00",
    likeCount: 89,
    isLiked: false
  },
  {
    id: 4,
    userId: 4,
    username: "青衣",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服摄影 | 唐制齐胸襦裙",
    content:
      "这次拍摄选择了唐制齐胸襦裙，搭配了传统发饰和配件，尝试还原古代美人的风韵。特别喜欢这组照片的意境！",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-17 09:20:00",
    updateTime: "2024-01-17 09:20:00",
    likeCount: 345,
    isLiked: true
  },
  {
    id: 5,
    userId: 5,
    username: "梨花白",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服约拍 | 魏晋风",
    content:
      "魏晋风格的汉服真的很有特色，这次约拍选择了古建筑作为背景，搭配飘逸的纱衣，效果出乎意料的好！",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-16 15:30:00",
    updateTime: "2024-01-16 15:30:00",
    likeCount: 167,
    isLiked: false
  },
  {
    id: 6,
    userId: 6,
    username: "初白",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服日常 | 简约风格",
    content:
      "分享一套简约风格的汉服日常，这种款式很适合平时穿着，不会太过繁复但又保留了传统美感。",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-15 11:25:00",
    updateTime: "2024-01-15 11:25:00",
    likeCount: 198,
    isLiked: false
  },
  {
    id: 7,
    userId: 7,
    username: "初白",
    avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
    title: "汉服日常 | 简约风格",
    content:
      "分享一套简约风格的汉服日常，这种款式很适合平时穿着，不会太过繁复但又保留了传统美感。",
    images: [
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
      "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
    ],
    createTime: "2024-01-15 11:25:00",
    updateTime: "2024-01-15 11:25:00",
    likeCount: 198,
    isLiked: false
  }
]);

// 上传配置
const uploadUrl = ref("https://api.example.com/upload");

// 添加状态
const imageVisible = ref(false);
const currentImages = ref<string[]>([]);

// 添加布局切换状态
const isVerticalLayout = ref(true);

// 方法定义
const handleAdd = () => {
  currentPost.value = null;
  postForm.title = "";
  postForm.content = "";
  postForm.images = [];
  dialogVisible.value = true;
};

const handleEdit = (post: SharingPost) => {
  currentPost.value = post;
  Object.assign(postForm, {
    title: post.title,
    content: post.content,
    images: [...post.images]
  });
  dialogVisible.value = true;
};

const handleDelete = (post: SharingPost) => {
  ElMessageBox.confirm("确定要删除这条分享吗？删除后不可恢复！", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      const index = sharingList.value.findIndex(p => p.id === post.id);
      if (index > -1) {
        sharingList.value.splice(index, 1);
        ElMessage.success("删除成功");
      }
    })
    .catch(() => {});
};

const handleLike = (post: SharingPost) => {
  post.isLiked = !post.isLiked;
  post.likeCount += post.isLiked ? 1 : -1;
};

const handleUploadSuccess = (response: any) => {
  if (response.url) {
    postForm.images.push(response.url);
    ElMessage.success("上传成功");
  }
};

const handleRemoveImage = (index: number) => {
  postForm.images.splice(index, 1);
};

const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(valid => {
    if (valid) {
      if (currentPost.value?.id) {
        // 编辑
        const index = sharingList.value.findIndex(
          p => p.id === currentPost.value?.id
        );
        if (index > -1) {
          sharingList.value[index] = {
            ...sharingList.value[index],
            title: postForm.title,
            content: postForm.content,
            images: [...postForm.images],
            updateTime: new Date().toLocaleString()
          };
        }
      } else {
        // 新增
        sharingList.value.unshift({
          id: Date.now(),
          userId: 1, // 当前用户ID
          username: "花想容", // 当前用户名
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          title: postForm.title,
          content: postForm.content,
          images: [...postForm.images],
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString(),
          likeCount: 0,
          commentCount: 0,
          isLiked: false
        });
      }

      ElMessage.success(currentPost.value?.id ? "更新成功" : "发布成功");
      dialogVisible.value = false;
    }
  });
};

// 修改图片预览方法
const handlePreviewImage = (images: string[], index: number) => {
  currentImages.value = images;
  imageVisible.value = true;

  // 添加遮罩层点击关闭事件
  nextTick(() => {
    const mask = document.querySelector(".el-image-viewer__mask");
    if (mask) {
      mask.addEventListener("click", () => {
        imageVisible.value = false;
      });
    }
  });
};

// 添加清理事件监听器的方法
const cleanupMaskListener = () => {
  const mask = document.querySelector(".el-image-viewer__mask");
  if (mask) {
    mask.removeEventListener("click", () => {
      imageVisible.value = false;
    });
  }
};

// 监听预览状态变化，在关闭时清理事件监听器
watch(imageVisible, newValue => {
  if (!newValue) {
    cleanupMaskListener();
  }
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  cleanupMaskListener();
});
</script>

<template>
  <div class="sharing-container">
    <el-card class="sharing-card">
      <div class="card-header">
        <div class="left">
          <span class="title">客片分享</span>
          <el-tag type="info" effect="plain" size="small">
            共 {{ sharingList.length }} 条分享
          </el-tag>
        </div>
        <div class="actions">
          <!-- 添加布局切换按钮 -->
          <el-button-group class="layout-switch">
            <el-button
              :type="isVerticalLayout ? 'primary' : 'default'"
              @click="isVerticalLayout = true"
            >
              <el-icon><Menu /></el-icon>
            </el-button>
            <el-button
              :type="!isVerticalLayout ? 'primary' : 'default'"
              @click="isVerticalLayout = false"
            >
              <el-icon><Grid /></el-icon>
            </el-button>
          </el-button-group>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>发布分享
          </el-button>
        </div>
      </div>

      <!-- 修改列表布局，使用动态类名 -->
      <div
        class="sharing-list"
        :class="{ 'vertical-layout': isVerticalLayout }"
      >
        <el-card
          v-for="post in sharingList"
          :key="post.id"
          class="sharing-item"
          shadow="hover"
        >
          <div class="post-header">
            <div class="user-info">
              <el-avatar :src="post.avatar" :size="40" />
              <div class="info">
                <span class="username">{{ post.username }}</span>
                <span class="time">{{ post.createTime }}</span>
              </div>
            </div>
            <div class="actions">
              <el-button-group>
                <el-button link type="primary" @click="handleEdit(post)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button link type="danger" @click="handleDelete(post)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </el-button-group>
            </div>
          </div>

          <div class="post-content">
            <div class="text-content">
              <h3 class="title">{{ post.title }}</h3>
              <p class="content">{{ post.content }}</p>
            </div>
            <div class="images">
              <el-image
                v-for="(image, index) in post.images.slice(0, 3)"
                :key="index"
                :src="image"
                fit="cover"
                class="image"
                @click="handlePreviewImage(post.images, index)"
              />
            </div>
          </div>

          <div class="post-footer">
            <div class="stats">
              <el-button
                link
                :type="post.isLiked ? 'danger' : 'default'"
                class="like-btn"
                @click="handleLike(post)"
              >
                <el-icon><Star /></el-icon>
                <span class="count">{{ post.likeCount }}</span>
              </el-button>
            </div>
            <span class="update-time">更新于 {{ post.updateTime }}</span>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 发布/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentPost?.id ? '编辑分享' : '发布分享'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="postForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="postForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入内容描述"
          />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <div class="upload-list">
            <div
              v-for="(image, index) in postForm.images"
              :key="index"
              class="upload-item"
            >
              <el-image :src="image" fit="cover" class="preview" />
              <div class="actions">
                <el-button
                  circle
                  link
                  type="danger"
                  @click="handleRemoveImage(index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <el-upload
              v-if="postForm.images.length < 9"
              class="upload-trigger"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              accept="image/*"
              multiple
            >
              <el-icon><Plus /></el-icon>
              <div class="upload-text">上传图片</div>
            </el-upload>
          </div>
          <div class="upload-tip">
            最多上传9张图片，当前已上传 {{ postForm.images.length }}/9
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="imageVisible"
      :url-list="currentImages"
      @close="imageVisible = false"
    />
  </div>
</template>

<style lang="scss" scoped>
.sharing-container {
  padding: 24px;
  background: var(--el-bg-color-page);

  .sharing-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding: 8px 0;

      .left {
        display: flex;
        align-items: center;
        gap: 12px;

        .title {
          font-size: 20px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          letter-spacing: 1px;
        }
      }

      .actions {
        display: flex;
        align-items: center;
        gap: 12px;

        .layout-switch {
          .el-button {
            padding: 8px 12px;
          }
        }
      }
    }

    .sharing-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 24px;
      padding: 4px;
      transition: all 0.3s;

      // 纵向布局样式
      &.vertical-layout {
        display: flex;
        flex-direction: column;
        gap: 20px;

        .sharing-item {
          .post-content {
            padding: 20px;
            display: flex;
            gap: 24px;

            .text-content {
              flex: 1;
              min-width: 0;
            }

            .images {
              flex: 0 0 auto;
              display: flex;
              gap: 12px;
              align-items: flex-start;

              .image {
                width: 160px;
                height: 160px;
              }
            }
          }
        }
      }

      // 网格布局样式
      &:not(.vertical-layout) {
        .sharing-item {
          .post-content {
            padding: 20px;
            display: block;

            .text-content {
              margin-bottom: 20px;
            }

            .images {
              display: grid;
              grid-template-columns: repeat(3, 1fr);
              gap: 12px;

              .image {
                width: 100%;
                aspect-ratio: 1;
              }
            }
          }
        }
      }

      // 共享的卡片样式
      .sharing-item {
        transition: all 0.3s;
        border-radius: 12px;
        overflow: hidden;

        &:hover {
          transform: translateY(-2px);
          box-shadow: var(--el-box-shadow);
        }

        .post-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
          background: var(--el-fill-color-light);
          border-bottom: 1px solid var(--el-border-color-lighter);

          .user-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .info {
              display: flex;
              flex-direction: column;
              gap: 4px;

              .username {
                font-size: 16px;
                font-weight: 500;
                color: var(--el-text-color-primary);
              }

              .time {
                font-size: 13px;
                color: var(--el-text-color-secondary);
              }
            }
          }
        }

        .post-content {
          padding: 20px;
          display: flex;
          gap: 24px;

          .text-content {
            flex: 1;
            min-width: 0;

            .title {
              font-size: 18px;
              font-weight: 600;
              color: var(--el-text-color-primary);
              margin-bottom: 12px;
            }

            .content {
              font-size: 14px;
              color: var(--el-text-color-regular);
              line-height: 1.8;
              margin-bottom: 16px;
            }
          }

          .images {
            flex: 0 0 auto;
            display: flex;
            gap: 12px;
            align-items: flex-start;

            .image {
              width: 160px;
              height: 160px;
              border-radius: 8px;
              object-fit: cover;
              cursor: pointer;
              transition: all 0.3s;
              border: 1px solid var(--el-border-color-lighter);
              box-shadow: var(--el-box-shadow-lighter);

              &:hover {
                transform: scale(1.02);
                border-color: var(--el-color-primary);
              }
            }
          }
        }

        .post-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 20px;
          background: var(--el-fill-color-light);
          border-top: 1px solid var(--el-border-color-lighter);

          .stats {
            .like-btn {
              display: flex;
              align-items: center;
              gap: 6px;
              padding: 6px 16px;
              border-radius: 16px;
              transition: all 0.3s;

              &:hover {
                background: var(--el-color-danger-light-9);
              }

              .count {
                font-weight: 500;
              }
            }
          }

          .update-time {
            font-size: 13px;
            color: var(--el-text-color-secondary);
          }
        }
      }
    }
  }
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;

  .upload-item {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 8px;
    overflow: hidden;

    .preview {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .actions {
      position: absolute;
      top: 4px;
      right: 4px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 50%;

      .el-button {
        color: #fff;

        &:hover {
          color: var(--el-color-danger);
        }
      }
    }
  }

  .upload-trigger {
    width: 120px;
    height: 120px;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: var(--el-text-color-secondary);
    transition: all 0.3s;

    .el-icon {
      font-size: 24px;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }

    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
    }
  }
}

.upload-tip {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}
</style>
